package com.example.bmi_kotlin

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.bmi_kotlin.databinding.ActivityMainBinding

class BMIActivity: AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        var view: View = binding.root
        setContentView(view)

        binding.btnConfirm.setOnClickListener(View.OnClickListener { // 获取输入的值
            val weightStr = binding.etWeight!!.text.toString()
            val heightStr: String = binding.etHeight.getText().toString()
            // 判断是否为空
            if (TextUtils.isEmpty(weightStr) || TextUtils.isEmpty(heightStr)) {
                Toast.makeText(this, "体重或身高不能为空", Toast.LENGTH_SHORT).show()
                return@OnClickListener
            }
            // 将字符串转为float，计算bmi
            val weight = weightStr.toFloat()
            val height = heightStr.toFloat()
            val bmi = weight / Math.pow(height.toDouble(), 2.0)
            binding.tvBmi!!.text = String.format("BMI： %.2f", bmi)
            binding.tvInfo.setText("诊断：" + getInfo(bmi))
            hideKeyboard(this)
        })
    }

    private fun getInfo(bmi: Double): String {
        // 获取RadiButton的文本
        val id = binding.rgSex!!.checkedRadioButtonId
        val btn: RadioButton = findViewById<RadioButton>(id)
        val sex = btn.text.toString()

        // 根据bmi得到信息
        var info = ""
        val isMan = sex == "男"
        info = if (bmi > 35 && isMan || bmi > 34 && !isMan) {
            "重度肥胖"
        } else if (bmi >= 30 && isMan || bmi >= 29 && !isMan) {
            "中度肥胖"
        } else if (bmi >= 27 && isMan || bmi >= 26 && !isMan) {
            "轻度肥胖"
        } else if (bmi >= 25 && isMan || bmi >= 24 && !isMan) {
            "体重超重"
        } else if (bmi >= 20 && isMan || bmi >= 19 && !isMan) {
            "体重正常"
        } else {
            "体重过轻"
        }
        return info
    }

    fun hideKeyboard(activity: Activity) {
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        var view = activity.currentFocus
        if (view == null) {
            view = View(activity)
        }
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun hideKeyboardFrom(context: Context, view: View) {
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}